package test;

import java.util.Objects;

public class PrinterDemo {

    public static Object lock = new Object();
    public final int max = 100;
    public int count = 0;

    private void printOdd(){
        while (count<=max){
            synchronized (lock){
                if(count%2==0){
                    //不能打
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }else {
                    //可以打
                    System.out.println(count++);
                    lock.notify();
                }
            }
        }
    }

    private void printEven(){
        while (count<=max){
            synchronized (lock){
                if(count%2==0){
                    //可以打
                    System.out.println(count++);
                    lock.notify();

                }else {
                    //不能打
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
    }


    public static void main(String[] args) {
        PrinterDemo printerDemo = new PrinterDemo();
        new Thread(printerDemo::printOdd).start();
        new Thread(printerDemo::printEven).start();

    }
}
